package com.jianganming.template.jdbc.framework;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JdbcTemplate<T> {

    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource){
        this.dataSource = dataSource;
    }

    public List<T> executeQuery(String sql, RowMapper<T> rowMapper, Object[] values)throws Exception{
        //1、获取连接
        Connection connection = dataSource.getConnection();
        //2、创建语句集
        PreparedStatement pstm = connection.prepareStatement(sql);
        //3、执行语句集
        ResultSet rs = execute(pstm,values);
        //4、处理结果集
        List<T> result = this.parseResultSet(rs,rowMapper);
        //5、关闭资源
        close(connection,pstm,rs);
        return result;

    }

    private List<T> parseResultSet(ResultSet rs, RowMapper<T> rowMapper)throws Exception {
        List<T> result = new ArrayList<T>();
        int rowNum = 0;
        while (rs.next()){
            result.add(rowMapper.mapRow(rs,rowNum++));
        }
        return result;

    }

    private ResultSet execute(PreparedStatement pstm, Object[] values)throws Exception {
        for (int i = 0; i < values.length; i++) {
            pstm.setObject(i+1,values[i]);
        }
        return pstm.executeQuery();

    }

    private void close(Connection connection, PreparedStatement statement, ResultSet resultSet)throws Exception {
        connection.close();
        statement.close();
        resultSet.close();
    }

}
